﻿using Newtonsoft.Json;
using Sustainalytics.Utils.Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace Sustainalytics.Utils.Logging
{
    public class SerilogControllerFilter : ActionFilterAttribute
    {

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var ctrlName = actionExecutedContext.ActionContext.ControllerContext.Controller.ToString();
            var methName = actionExecutedContext.Request.Method.ToString();
            var requestUri = actionExecutedContext.Request.RequestUri.ToString();
            var args = string.Empty;
            var reasonPhrase = string.Empty;
            var exceptionMessage = string.Empty;


            if (actionExecutedContext.ActionContext.ActionArguments != null)
            {
                if (actionExecutedContext.ActionContext.ActionArguments.ContainsKey("__duration"))
                {
                    actionExecutedContext.ActionContext.ActionArguments.Remove("__duration");
                }
                args = JsonConvert.SerializeObject(actionExecutedContext.ActionContext.ActionArguments);

                if (args.Length > 1024)
                    args = args.Substring(0, 1024);
            }

            if (actionExecutedContext.Response != null)
            {
                reasonPhrase = actionExecutedContext.Response.ReasonPhrase;

                if (actionExecutedContext.Response.IsSuccessStatusCode)
                {
                    CommonEventSerilog.Log.LogWebRequestSuccess(methName, requestUri, ctrlName, args, reasonPhrase);
                }
                else
                {
                    if (((System.Net.Http.ObjectContent)actionExecutedContext.Response.Content).Value != null)
                    {
                        exceptionMessage = ((System.Net.Http.ObjectContent)actionExecutedContext.Response.Content).Value.ToString();
                    }
                    CommonEventSerilog.Log.LogWebRequestError(methName, requestUri, ctrlName, args, reasonPhrase, exceptionMessage);
                }
            }
        }
    }
}
